package com.xiaohao.server.parkmap.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaohao.server.parkmap.entity.Article;
import com.xiaohao.server.parkmap.mapper.ArticleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.List;
import java.util.Objects;

@Service
public class ArticleService {
    @Autowired
    private ArticleMapper articleMapper;

    public Article queryById(Integer id) {
        Article article = articleMapper.selectById(id);
        Article save = new Article().setId(id).setCount(article.getCount() + 1);
        save(save);
        return article;
    }

    public Article queryOne(Article article) {
        return articleMapper.selectOne(new QueryWrapper<>(article));
    }

    public List<Article> query(Article article) {
        LambdaQueryWrapper<Article> queryWrapper =
            new LambdaQueryWrapper<>(article).select(Article.class,
                tableFieldInfo -> !tableFieldInfo.getColumn().equals("content"));
        return articleMapper.selectList(queryWrapper);
    }

    public Integer delete(Integer id) {
        return articleMapper.deleteById(id);
    }

    public Integer save(Article article) {
        if (Objects.nonNull(article) && Objects.nonNull(article.getId())) {
            return articleMapper.updateById(article);
        } else {
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            article.setCount(0);
            article.setDate(timestamp);
            return articleMapper.insert(article);
        }
    }
}
